//
//  KACloseAccVC.swift
//  kano
//
//  Created by Sophia on 2024/8/22.
//

import UIKit
import RxCocoa
import RxSwift
import PopupDialog

class KACloseAccVC: KABaseVC {
    private let disposeBag = DisposeBag()
    //picture code
    var captchaCode: String = ""
    //voice code / msg code
    var currentCodeType: String = ""

    private var captchaId: String = ""
    private var codeToken: String = ""
    private var verifyToken: String = ""
    
    //Timer
    private var count: Int = 60
    private var task: String?
    
    lazy var var_cornerView: UIView = {
        let var_cornerView = UIView()
        var_cornerView.backgroundColor = UIColor.white
        var_cornerView.layer.cornerRadius = kscale(30)
        var_cornerView.layer.masksToBounds = true
        var_cornerView.frame = CGRectMake(kscale(20), UIDevice.ka_fullNavHeight+kscale(40), var_screenWidth-kscale(40), kscale(330))
        return var_cornerView
    }()
    
    lazy var var_titleLabel: UILabel = {
        let var_titleLabel = UILabel()
        var_titleLabel.x = kscale(20)
        var_titleLabel.y = kscale(32)
        var_titleLabel.width = var_cornerView.width-kscale(40)
        var_titleLabel.height = kscale(32)
        var_titleLabel.textAlignment = .center
        var_titleLabel.numberOfLines = 0
        var_titleLabel.font = UIFont.systemFont(ofSize: kscale(24), weight: .bold)
        var_titleLabel.textColor = .black
        var_titleLabel.text = "Verify Linked Phone"
        var_titleLabel.adjustsFontSizeToFitWidth = true
        return var_titleLabel
    }()
    
    lazy var var_tipLabel: UILabel = {
        let var_tipLabel = UILabel()
        var_tipLabel.x = kscale(20)
        var_tipLabel.y = kscale(72)
        var_tipLabel.width = var_cornerView.width-kscale(40)
        var_tipLabel.height = kscale(20)
        var_tipLabel.numberOfLines = 0
        var_tipLabel.font = UIFont.systemFont(ofSize: kscale(16), weight: .regular)
        var_tipLabel.textAlignment = .center
        var_tipLabel.textColor = .black
        var_tipLabel.adjustsFontSizeToFitWidth = true
        var_tipLabel.text = "The verification code has been sent to \(KAUserManager.shared.user.mobile.maskedNumber)"
        return var_tipLabel
    }()
    
    lazy var var_codeView: KAPwdView = {
        var_codeView = KAPwdView(placeHolder: "Please enter the verification code", limit: 6)
        var_codeView.rightBtn.isHidden = true
        var_codeView.contentTF.isSecureTextEntry = false
        var_codeView.contentTF.keyboardType = .numberPad;
        var_codeView.x = kscale(20)
        var_codeView.y = var_tipLabel.bottom + kscale(32)
        var_codeView.size = CGSizeMake(var_cornerView.width-kscale(40), kscale(48))
        return var_codeView
    }()
    
    lazy var msgCodeBtn: UIButton = {
        let msgCodeBtn = UIButton()
        msgCodeBtn.titleLabel?.textAlignment = .right
        msgCodeBtn.setTitle("Get Verification Code", for: .normal)
        msgCodeBtn.setTitleColor(.themeColor, for: .normal)
        msgCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        msgCodeBtn.addTarget(self, action: #selector(ka_sendCodeButtonClick), for: .touchUpInside)
        return msgCodeBtn
    }()
    
    private let voiceCodeBtn: UIButton = {
        let voiceCodeBtn = UIButton()
        voiceCodeBtn.backgroundColor = .colorf2f2f5
        voiceCodeBtn.setTitle("Voice code", for: .normal)
        voiceCodeBtn.setTitleColor(.themeColor, for: .normal)
        voiceCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(13), weight: .regular)
        voiceCodeBtn.addTarget(KAOTPVC.self, action: #selector(ka_sendCodeButtonClick), for: .touchUpInside)
        return voiceCodeBtn
    }()
    
    lazy var var_colseBtn: UIButton = {
        let var_colseBtn = UIButton(frame: CGRectMake(kscale(48), var_codeView.bottom+kscale(60), var_cornerView.width-kscale(96), kscale(50.0)))
        var_colseBtn.setTitle("OK", for: .normal)
        var_colseBtn.setTitleColor(.white, for: .normal)
        var_colseBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_colseBtn.backgroundColor = .colorBDBDF5
        var_colseBtn.layer.cornerRadius = kscale(25)
        var_colseBtn.layer.masksToBounds = true
        var_colseBtn.addTarget(self, action: #selector(ka_closeButtonClick), for: .touchUpInside)
        return var_colseBtn
    }()
    lazy var var_pictureView: KAPictureVerifyView = {
        let var_pictureView = KAPictureVerifyView { [self] code, captcheId in
            captchaId = captcheId
            captchaCode = code
            ka_sendCode(withType: "0")
        }
        return var_pictureView
    }()
}

extension KACloseAccVC {
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_setUI()
        ka_bindUI()
        ka_checkMobile()
    }
    
    func ka_setUI() {
        view.backgroundColor = .colorf2f2f5
        ka_showCustomerNavBar(type: .normal)
        var_navBar.updateUI(alpha: 0)
        
        view.addSubview(var_cornerView)
        var_cornerView.addSubview(var_titleLabel)
        var_cornerView.addSubview(var_tipLabel)
        var_cornerView.addSubview(var_codeView)
        var_cornerView.addSubview(msgCodeBtn)
        var_cornerView.addSubview(var_colseBtn)
        
        msgCodeBtn.snp.makeConstraints { make in
            make.right.equalTo(var_cornerView).offset(kscale(-20))
            make.top.equalTo(var_codeView.snp.bottom).offset(kscale(12))
        }
    }
    
    func ka_bindUI() {
        var_codeView.contentTF.rx.text
            .orEmpty
            .map { text in
                return (text.count == 6) ? .themeColor : .colorBDBDF5
            }
            .bind(to: var_colseBtn.rx.backgroundColor)
            .disposed(by: disposeBag)
    }
    
    
    @objc func ka_sendCodeButtonClick() {
        ka_sendCode(withType: "0")
    }
    
    func ka_checkMobile() {
        NetService.ka_checkMobileWith(mobile: KAUserManager.shared.user.mobile) { [self] isSuccess, message, response in
            if isSuccess {
                guard let user = response?.content else { return }
                codeToken = user.codeToken
                ka_sendCode(withType: "0")
            }
        }
    }
    
    private func ka_sendCode(withType codeType: String) {
        currentCodeType = codeType
        NetService.ka_sentCode(withType: codeType, codeToken: codeToken, operationType: .logoff, captchaCode: captchaCode) { [self] isSuccess, message, response in
            self.captchaId = ""
            self.captchaCode = ""
            if isSuccess {
                self.view.makeToast("The verification code is sent successfully.")
                if response?.content != nil {
                    self.verifyToken = response!.content!.codeToken
                }
                startTimer()
                self.var_pictureView.dismiss()
            } else {
                guard let status = response?.status else { return }
                if status == 1015 || status == 1016 || status == 1617 || status == 1618 || status == 1619 || status == 1014 || status == 1010 || status == 1017 || status == 7006 || status == 7007 || status == 7008  {
                    self.var_pictureView.show()
                    self.var_pictureView.makeToast(message)
                    return
                }
                self.view.makeToast(message)
                self.var_pictureView.dismiss()
            }
        }
    }
    
    @objc func ka_closeButtonClick() {
        guard var_codeView.contentTF.text?.count == 6 else {
            return view.makeToast("Please enter the correct verification code")
        }
        
        let paramDic: [String: Any] = [
          "mobile": KAUserManager.shared.user.mobile,
          "zuid": UIDevice.ka_UUID,
          "operationType": KAOperation.logoff.rawValue,
          "verifyCode": var_codeView.contentTF.text!,
          "verifyToken": verifyToken,
          "codeToken": codeToken,
        ]
        view.showLoading()
        loginProvider.request(.logOff(paramDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let status = response?.status else {
                                view.makeToast("Verification failure"); return
                            }
                            if status == 0 {
                                showAlert()
                                return
                            }
                            view.makeToast("Verification failure")
                        } else {
                            self.view.makeToast(message)
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }

    func showAlert() {
        let alertVC = KAAlertVC(title: "Cancellation Request Submitted", subTitle: "We will process your request and delete all your data within 15 days. If you log in again within 15 days, you can withdraw the cancellation request Complete and Exit", actionTitle: "Complete and Exit", image: "alert_complete")
        let popup = PopupDialog(viewController: alertVC, buttonAlignment: .horizontal, transitionStyle: .zoomIn, tapGestureDismissal: false, panGestureDismissal: false)
        alertVC.handler = {
            popup.dismiss()
            KADBDBManager.ka_removeCurrentUser()
            KAUserManager.shared.userLogout()
        }
        let containerAppearance = PopupDialogContainerView.appearance()
        containerAppearance.cornerRadius = 20
        self.present(popup, animated: true, completion: nil)
    }
}

extension KACloseAccVC {
    private func startTimer() {
        count = 60
        task = KATimer.execTask(self, selector: #selector(countdown), start: 0.0, interval: 1.0, repeats: true, async: false)
    }
    
    @objc private func countdown() {
        let button: UIButton = (currentCodeType == "0") ? msgCodeBtn : voiceCodeBtn
        if count > 0 {
            count -= 1
            button.isUserInteractionEnabled = false
            button.setTitleColor(.themeColor, for: .normal)
            button.setTitle("\(count)s", for: .normal)
        } else {
            KATimer.cancelTask(task!)
            button.setTitleColor(.themeColor, for: .normal)
            button.isUserInteractionEnabled = true
            if currentCodeType == "0" {
                voiceCodeBtn.isHidden = false
                button.setTitle("Resend", for: .normal)
            } else {
                button.setTitle("Voice code", for: .normal)
            }
        }
    }
}
